﻿using System.Collections.Generic;
using OfficeOpenXml;

namespace Jaiden.Data.Exporting
{
    public class EPPlusExportTarget : IExportTarget
    {
        private readonly ExcelPackage _excelPackage;

        public EPPlusExportTarget(ExcelPackage excelPackage)
        {
            _excelPackage = excelPackage;
        }

        public void Export<T>(IEnumerable<T> data, IExportRole<T> role)
        {
            var sheet = _excelPackage.Workbook.Worksheets[role.Name] ??
                        _excelPackage.Workbook.Worksheets.Add(role.Name);
            sheet.OutLineApplyStyle = true;

            for (var i = 0; i < role.Columns.Count; i++)
            {
                var cell = sheet.Cells[1, i + 1];
                cell.Value = role.Columns[i].Name;
                cell.Style.Font.Bold = true;
            }

            var r = 1;
            foreach (var item in data)
            {
                r++;
                for (var c = 0; c < role.Columns.Count; c++)
                    sheet.Cells[r, c + 1].Value = role.Columns[c].ValueGetter(item);
            }
        }
    }
}